import { defineStore } from 'pinia'
import { reqLogin, reqUserInfo, reqLogout } from '@/api/user'
import { GET_TOKEN, SET_TOKEN, REMOVE_TOKEN } from '@/utils/token'
import { constantRoute, anyRoutes, asyncRoutes } from '@/router/router'
import type { loginFormData, loginRes, userInfoRes } from '@/api/user/type'
import router from '@/router'

function fillRoutes(async: any, userRoutes: any) {
  return async.filter((item: any) => {
    if (userRoutes.includes(item.name)) {
      if (item.children && item.children.length > 0) {
        item.children = fillRoutes(item.children, userRoutes)
      }
      return item
    }
  })
}

const useUserStore = defineStore('user', {
  state() {
    return {
      token: GET_TOKEN(),
      menuRoutes: constantRoute,
      userInfo: {},
    }
  },
  actions: {
    async getLogin(loginFrom: loginFormData) {
      const res: loginRes = await reqLogin(loginFrom)
      if (res.code == 200) {
        this.token = res.data
        SET_TOKEN(res.data)
        return 'ok'
      } else {
        return Promise.reject(new Error(res.data))
      }
    },
    async getUserInfo() {
      const res: userInfoRes = await reqUserInfo()
      if (res.code == 200) {
        this.userInfo = res.data
        let async = fillRoutes(JSON.parse(JSON.stringify(asyncRoutes)), res.data.routes)
        // let async = fillRoutes(asyncRoutes, res.data.routes)
        this.menuRoutes = [...constantRoute, ...async, ...anyRoutes]
        let someRoutes = [...async, ...anyRoutes]
        someRoutes.forEach((item: any) => {
          router.addRoute(item)
        })
        return 'ok'
      } else {
        return Promise.reject(new Error('获取失败'))
      }
    },
    async getLogout() {
      const res: any = await reqLogout()
      if (res.code == 200) {
        this.userInfo = {}
        this.token = ''
        REMOVE_TOKEN()
        return 'ok'
      } else {
        return Promise.reject(new Error(res.message))
      }
    },
  },
  getters: {
    userName(state: any) {
      return state.userInfo.name
    },
    avator(state) {
      return state.userInfo.avatar
    },
  },
})

export default useUserStore
